package com.jungle.jedis;

import com.jungle.serializer.Serializer;
import org.springframework.beans.factory.InitializingBean;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

public class JedisTemplate implements InitializingBean {

    //是否集群模式
    private boolean       cluster          = false;

    private JedisPool jedisPool;

    private JedisCluster jedisCluster;

    private JedisOperator jedisOperator;

    private Serializer keySerializer;

    private Serializer    valSerializer;

    public JedisTemplate(){

    }

    public JedisTemplate(JedisPool jedisPool){
        this.jedisPool = jedisPool;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    public <E> E get(Object key){
        if(key==null){
            return null;
        }
        if(cluster){
            return (E)deserializeVal(jedisCluster.get(serialize(key)));
        }
        else {
            return (E)deserializeVal(jedisOperator.get(serialize(key)));
        }
    }

    public <T> T deserializeVal(final byte[] bytes){
        return (T)valSerializer.deserialize(bytes);
}

    public byte[] serialize(Object key){
        return keySerializer.serialize(key);
    }

    public boolean set(String key, Object value) {
        if(key==null||value==null){
            return false;
        }
        if(cluster){
            return jedisCluster.set(serializeKey(key), serializeVal(value)).equals("OK");
        }
        else {
            return jedisOperator.set(serializeKey(key), serializeVal(value)).equals("OK");
        }

    }

    private byte[] serializeVal(Object value) {
        return valSerializer.serialize(value);
    }

    private byte[] serializeKey(String key) {
        return keySerializer.serialize(key);
    }

    public boolean set(String key, Object value, int ttl) {
        if(key==null||value==null){
            return false;
        }
        if(cluster){
            return jedisCluster.setex(serializeKey(key), ttl, serializeVal(value)).equals("OK");
        }
        else{
            return jedisOperator.setex(serializeKey(key), ttl, serializeVal(value)).equals("OK");
        }
    }

    public boolean del(String key) {
            if(key==null){
                return false;
            }
            if(cluster){
               return this.jedisCluster.del(serializeKey(key))!=0;
            }
            else{
                return this.jedisOperator.del(serializeKey(key))!=0;
            }
    }

    public JedisOperator getJedisOperator() {
        return jedisOperator;
    }

    public void setJedisOperator(JedisOperator jedisOperator) {
        this.jedisOperator = jedisOperator;
    }
}
